package com.liuyonggang.generator.ui;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;

import javax.swing.filechooser.FileSystemView;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.liuyonggang.generator.util.CodeGenerator;
import com.liuyonggang.generator.util.DatabaseInfoOp;
import com.liuyonggang.generator.util.PropertyConfig;

/**
 * 代码生成器
 * @author Yonggang.Liu
 *
 */
public class MainConsole {
	private static Logger logger = LoggerFactory.getLogger(CodeGenerator.class);
	
	public static void main(String[] args) {
		
		PropertyConfig.loadPropertyFile("config.properties");
		
		String driver=PropertyConfig.getProperty("jdbc.driver");
		String url=PropertyConfig.getProperty("jdbc.url");
		String username=PropertyConfig.getProperty("jdbc.username");
		String password=PropertyConfig.getProperty("jdbc.password");
		
		String tableName=PropertyConfig.getProperty("tableName");
		String description=PropertyConfig.getProperty("description");

		String author=PropertyConfig.getProperty("author");
		String packagePath=PropertyConfig.getProperty("packagePath");
		String sourcePath=PropertyConfig.getProperty("outPath");
		String contact=PropertyConfig.getProperty("contact");
		String template=PropertyConfig.getProperty("template");

		//是否去掉数据库前缀
		CodeGenerator.prefix="";

		//输出路径
		if(StringUtils.isBlank(sourcePath)){
			//获取当前用户桌面路径
			FileSystemView fsv=FileSystemView.getFileSystemView();
			sourcePath=fsv.getHomeDirectory().toString();
	    }
		
	    sourcePath += File.separator + "src"+File.separator;
	    logger.info(sourcePath);
		
		
		Connection conn = new DatabaseInfoOp(driver, url, username, password).getConnectionByJDBC();
		if(null != conn){
			 logger.info("连接成功");
			 boolean flag = new CodeGenerator().generator(template,driver, url, username, password,tableName, packagePath, author, contact, sourcePath, description);
				if(flag){
					//打开文件夹
					try {
						Runtime.getRuntime().exec("cmd.exe /c start "+ sourcePath);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
		} else{
			logger.info("数据库连接失败，请检查后重试！");
		}
	}

}
